from os import fdopen, remove
from StringIO import StringIO
from tempfile import mkstemp

from networkx import read_graphml

from ._viewer import Main as Viewer



_NODE = """\
ncols 1
nrows 1
cellsize %s
1"""

_S_GRAPH = """\
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
			     http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">

  <key id="data" for="node" attr.name="data" attr.type="string" />
  <key id="img" for="node" attr.name="img" attr.type="string" />
  <key id="x" for="edge" attr.name="x" attr.type="int" />
  <key id="y" for="edge" attr.name="y" attr.type="int" />

  <graph id="lite" edgedefault="directed">
    <!-- nodes -->
    <node id="0">
      <data key="data">%s</data>
      <data key="img">%s</data>
    </node>
  </graph>

</graphml>"""


def lite(viewer_rect, pos, node_size, graph_img, zoom_out_limit=1, **kw):
    fd_node, f_node_name = mkstemp()
    f_node = fdopen(fd_node, 'w')
    f_node.write(_NODE%str(node_size))
    f_graph = StringIO(_S_GRAPH%(f_node_name, graph_img))
    f_node.close()
    graph = read_graphml(f_graph)
    viewer = Viewer(viewer_rect.size, pos, '0', graph, viewer_rect,
                    zoom_out_limit=zoom_out_limit, **kw)
    remove(f_node_name)
    return viewer
